package utils

import (
	"bufio"
	"os"
	"strings"
)

// TrieNode 定义字典树的节点
type TrieNode struct {
	children map[rune]*TrieNode
	isEnd    bool
}

// Trie 定义字典树
type Trie struct {
	root *TrieNode
}

// NewTrie 创建一个新的字典树
func NewTrie() *Trie {
	return &Trie{root: &TrieNode{children: make(map[rune]*TrieNode)}}
}

// Insert 向字典树中插入一个违规词
func (t *Trie) Insert(word string) {
	node := t.root
	for _, char := range word {
		if _, exists := node.children[char]; !exists {
			node.children[char] = &TrieNode{children: make(map[rune]*TrieNode)}
		}
		node = node.children[char]
	}
	node.isEnd = true
}

// Search 检查字典树中是否有违规词
func (t *Trie) Search(text string) bool {
	node := t.root
	for _, char := range text {
		if _, exists := node.children[char]; !exists {
			return false
		}
		node = node.children[char]
		if node.isEnd {
			return true
		}
	}
	return false
}

// Filter 过滤文本中的违规词
func Filter(text string, trie *Trie) string {
	var result []rune
	start := 0
	for i := range text {
		// 以当前字符为起始位置，检查是否有违规词
		if trie.Search(text[start : i+1]) {
			// 如果找到违规词，将其替换为星号
			result = append(result, []rune(strings.Repeat("*", i-start+1))...)
			start = i + 1
		}
	}
	result = append(result, []rune(text[start:])...)
	return string(result)
}

// 读取文件内容
func readFile(filePath string) (string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	var content strings.Builder
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		content.WriteString(scanner.Text() + "\n")
	}
	if err := scanner.Err(); err != nil {
		return "", err
	}
	return content.String(), nil
}

// 写入处理后的内容到文件
func writeFile(filePath, content string) error {
	file, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = file.WriteString(content)
	return err
}
